/*
Copyright [2020] [https://www.xiaonuo.vip]

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

Snowy采用APACHE LICENSE 2.0开源协议，您在使用过程中，需要注意以下几点：

1.请不要删除和修改根目录下的LICENSE文件。
2.请不要删除和修改Snowy源码头部的版权声明。
3.请保留源码和相关描述文件的项目出处，作者声明等。
4.分发源码时候，请注明软件出处 https://gitee.com/xiaonuobase/snowy-layui
5.在修改包名，模块名称，项目代码等时，请注明软件出处 https://gitee.com/xiaonuobase/snowy-layui
6.若您的项目无法满足以上几点，可申请商业授权，获取Snowy商业授权许可，请在官网购买授权，地址为 https://www.xiaonuo.vip
 */
package vip.xiaonuo.sys.modular.question.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import com.alibaba.fastjson.JSONObject;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import vip.xiaonuo.core.annotion.BusinessLog;
import vip.xiaonuo.core.annotion.Permission;
import vip.xiaonuo.core.context.login.LoginContextHolder;
import vip.xiaonuo.core.enums.LogAnnotionOpTypeEnum;
import vip.xiaonuo.core.pojo.login.SysLoginUser;
import vip.xiaonuo.core.pojo.page.PageResult;
import vip.xiaonuo.core.pojo.response.ResponseData;
import vip.xiaonuo.core.pojo.response.SuccessResponseData;
import vip.xiaonuo.sys.modular.question.entity.*;
import vip.xiaonuo.sys.modular.question.mapper.BigquestionteMapper;
import vip.xiaonuo.sys.modular.question.mapper.ExaminationrecordMapper;
import vip.xiaonuo.sys.modular.question.mapper.SmallquestionteMapper;
import vip.xiaonuo.sys.modular.question.mapper.TestpapermxMapper;
import vip.xiaonuo.sys.modular.question.param.TestpaperParam;
import vip.xiaonuo.sys.modular.question.service.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 问卷列表控制器
 *
 * @author lxc
 * @date 2024-03-04 11:34:58
 */
@Controller
public class TestpaperController {

    private String PATH_PREFIX = "system/sysQuestion/testpaper/";

    @Resource
    private TestpaperService testpaperService;
    @Resource
    private TestpapermxMapper testpapermxMapper;
    /**
     * 单选
     */
    @Resource
    private SingleelectionService singleelectionService;
    /**
     * 多选
     */
    @Resource
    private MultipleselectionService multipleselectionService;
    /**
     * 判断
     */
    @Resource
    private JudgementquestionService judgementquestionService;
    /**
     * 填空
     */
    @Resource
    private CompletionService completionService;
    /**
     * 问答
     */
    @Resource
    private LargequestionService largequestionService;

    @Resource
    private SmallquestionteMapper smallquestionteMapper;
    @Resource
    private BigquestionteMapper bigquestionteMapper;
    @Resource
    private SmallquestionteService smallquestionteService;
    @Resource
    private BigquestionteService bigquestionteService;

    @Resource
    private BigquestionfoService bigquestionfoService;
    @Resource
    private SmallquestionfoService smallquestionfoService;

    @Resource
    private ExaminationrecordMapper examinationrecordMapper;

    /**
     * 问卷列表页面
     *
     * @author lxc
     * @date 2024-03-04 11:34:58
     */
    @Permission
    @GetMapping("/sysQuestionnaire/list")
    public String index() {
        return "system/sysQuestion/testpaper/index.html";
    }

    /**
     * 用户问卷列表
     *
     * @author lxc
     * @date 2024-03-04 11:34:58
     */
    @Permission
    @GetMapping("/sysQuestionnaire/listMy")
    public String indexMy() {
        return "system/sysQuestion/testpaper/index_my.html";
    }

    /**
     * 用户问卷统计页面
     *
     * @author ssh
     * @date 2024-08-27 17:34:58
     */
    @Permission
    @GetMapping("/sysQuestionnaire/statistics")
    public String statistics() {
        return "system/sysQuestion/testpaper/statistics.html";
    }

    /**
     * 用户问卷问答统计页面
     *
     * @author ssh
     * @date 2024-08-27 17:34:58
     */
    @Permission
    @GetMapping("/sysQuestionnaire/statisticsAnswer")
    public String statisticsAnswer() {
        return "system/sysQuestion/testpaper/answerAnaly.html";
    }

    /**
     * 在线考试页面
     *
     * @author lxc
     * @date 2024-06-18 11:00:58
     */
    @Permission
    @GetMapping("/sysQuestionnaire/testpaperExa")
    public String testPaperExa() {
        return "system/sysQuestion/testpaper/testpaper_exa.html";
    }

    /**
     * 用户信息
     *
     * @author lxc
     * @date 2024-08-1 11:00:58
     */
    @GetMapping("/testpaper/userInfo")
    public String userInfo() {
        return "system/sysQuestion/testpaper/userInfo.html";
    }

    /**
     * 用户问卷添加
     *
     * @author lxc
     * @date 2024-03-04 11:34:58
     */
    @Permission
    @ResponseBody
    @PostMapping("/sysQuestionnaire/add")
    public JSONObject add(@RequestBody Examinationrecord examinationrecord) {
        SysLoginUser sysLoginUser = LoginContextHolder.me().getSysLoginUser();
        String msg = "success";
        JSONObject jsonObject = new JSONObject();
        examinationrecord.setUserId(sysLoginUser.getId());
        //查询记录
        List<Examinationrecord> examinationrecordList = examinationrecordMapper.queryByUserId(examinationrecord);
        //判断是否已经做过调查问卷
        List<Map<String, Object>> mapList = testpaperService.queryIsAnswer(examinationrecord);
        if (mapList.size() < 1) {
            //删除记录表数据，避免出现多余的数据
            if (examinationrecordList.size() > 0) {
                smallquestionteMapper.deleteByUserId(examinationrecord.getTestpaperId(), sysLoginUser.getAccount());
                bigquestionteMapper.deleteByUserId(examinationrecord.getTestpaperId(), sysLoginUser.getAccount());
                examinationrecordMapper.deleteByUserId(examinationrecord);
            }
            Examinationrecord recode = testpaperService.addRecord(examinationrecord);
            //初始作答
            this.addQuestionte(examinationrecord);
            jsonObject.put("msg", msg);
            jsonObject.put("recode", recode);
        } else {
            msg = "fail";
            jsonObject.put("msg", msg);
            jsonObject.put("recode", "201");
        }
        return jsonObject;
    }

    public void addQuestionte(Examinationrecord examinationrecord) {
        SysLoginUser sysLoginUser = LoginContextHolder.me().getSysLoginUser();
        Testpaper testpaper = testpaperService.getById(examinationrecord.getTestpaperId());
        List<Testpapermx> testpapermxList = testpapermxMapper.selectByTestId(testpaper.getTestpaperId());
        for (Testpapermx testpapermx : testpapermxList) {
            String[] selecttops = testpapermx.getSelectedtopics().split(",");
            String type = testpapermx.getType();
            List<Map<String, Object>> mapList = new ArrayList<>();
            switch (type) {
                case "0":
                    mapList = singleelectionService.getListByIds(selecttops);
                    break;
                case "1":
                    mapList = multipleselectionService.getListByIds(selecttops);
                    break;
                case "2":
                    mapList = judgementquestionService.getListByIds(selecttops);
                    break;
                case "3":
                    mapList = completionService.getListByIds(selecttops);
                    break;
                case "4":
                    mapList = largequestionService.getListByIds(selecttops);
                    break;
            }
            for (int i = 0; i < mapList.size(); i++) {
                String ids = mapList.get(i).get("id").toString();
                if ("0".equals(type) || "1".equals(type) || "2".equals(type)) {
                    Smallquestionte smallquestionte = new Smallquestionte();
                    smallquestionte.setQuestionsId(ids);
                    smallquestionte.setTestpaperId(examinationrecord.getTestpaperId());
                    smallquestionte.setUsername(sysLoginUser.getUsername());
                    smallquestionte.setType(type);
                    smallquestionte.setExaminationrecordId(examinationrecord.getId());
                    smallquestionteMapper.insert(smallquestionte);
                } else {
                    Bigquestionte bigquestionte = new Bigquestionte();
                    bigquestionte.setQuestionsId(ids);
                    bigquestionte.setTestpaperId(examinationrecord.getTestpaperId());
                    bigquestionte.setUsername(sysLoginUser.getUsername());
                    bigquestionte.setType(type);
                    bigquestionte.setExaminationrecordId(examinationrecord.getId());
                    bigquestionteMapper.insert(bigquestionte);
                }
            }
        }

    }


    /**
     * 修改选中状态
     *
     * @param smallquestionte
     */
    @Permission
    @ResponseBody
    @PostMapping("/smallquestionte/edit")
    public void smallEdit(@RequestBody Smallquestionte smallquestionte) {
        smallquestionteService.editUserAnswer(smallquestionte);
    }

    /**
     * 修改选中状态
     *
     * @param bigquestionte
     */
    @Permission
    @ResponseBody
    @PostMapping("/bigquestionte/edit")
    public void bigEdit(@RequestBody Bigquestionte bigquestionte) {
        bigquestionteService.editUserAnswer(bigquestionte);
    }

    /**
     * 问卷列表表单页面
     *
     * @author lxc
     * @date 2024-03-04 11:34:58
     */
    @GetMapping("/testpaper/form")
    public String form() {
        return PATH_PREFIX + "form.html";
    }

    /**
     * 问卷记录
     *
     * @author lxc
     * @date 2024-03-04 11:34:58
     */
    @Permission
    @GetMapping("/testpaper/recordList")
    public String recordList() {
        return "system/sysQuestion/testpaper/recordList.html";
    }

    /**
     * 问卷列表表单页面
     *
     * @author lxc
     * @date 2024-03-04 11:34:58
     */
    @GetMapping("/testpaper/extForm")
    public String extForm() {
        return PATH_PREFIX + "extForm.html";
    }

    /**
     * 问卷列表表单页面
     *
     * @author lxc
     * @date 2024-03-04 11:34:58
     */
    @GetMapping("/testpaper/testpaper_view")
    public String view() {
        return PATH_PREFIX + "testpaper_view.html";
    }

    /**
     * 查询问卷列表
     *
     * @author lxc
     * @date 2024-03-04 11:34:58
     */
    @Permission
    @ResponseBody
    @GetMapping("/testpaper/page")
    @BusinessLog(title = "问卷列表_查询", opType = LogAnnotionOpTypeEnum.QUERY)
    public PageResult<Testpaper> page(TestpaperParam testpaperParam) {
        return testpaperService.page(testpaperParam);
    }

    /**
     * 问卷记录
     *
     * @author lxc
     * @date 2024-03-04 11:34:58
     */
    @ResponseBody
    @GetMapping("/testpaper/pageRecorde")
    @BusinessLog(title = "问卷列表_查询", opType = LogAnnotionOpTypeEnum.QUERY)
    public PageResult<Examinationrecord> pageRecorde(Examinationrecord examinationrecord) {
        return testpaperService.pageRecorde(examinationrecord);
    }

    /**
     * 添加问卷列表
     *
     * @author lxc
     * @date 2024-03-04 11:34:58
     */
    @Permission
    @ResponseBody
    @PostMapping("/testpaper/add")
    @BusinessLog(title = "问卷列表_增加", opType = LogAnnotionOpTypeEnum.ADD)
    public ResponseData add(@RequestBody @Validated(TestpaperParam.add.class) TestpaperParam testpaperParam) {
        testpaperService.add(testpaperParam);
        return new SuccessResponseData();
    }

    /**
     * 问卷提交
     *
     * @author lxc
     * @date 2024-06-19 11:00:58
     */
    @Permission
    @ResponseBody
    @PostMapping("/testpaper/commits")
    @BusinessLog(title = "问卷列表_增加", opType = LogAnnotionOpTypeEnum.ADD)
    public ResponseData commits(@RequestBody Achievement achievement) {
        //保存答题
        JSONObject jsonObject = new JSONObject();
        String code = "success";
        String msg = "";
        try {
            //提交试卷更改已完成状态(state=1)
            bigquestionfoService.updateStateById(achievement);
            bigquestionfoService.saveByExamId(achievement);
            smallquestionfoService.saveByExamId(achievement);
            bigquestionfoService.deleteByExemId(achievement);
            smallquestionfoService.deleteByExemId(achievement);
        } catch (Exception e) {
            e.printStackTrace();
            code = "fail";
            msg = e.getMessage();
        }
        jsonObject.put("cdode", code);
        jsonObject.put("msg", msg);
        return new SuccessResponseData(jsonObject);
    }

    /**
     * 删除问卷列表
     *
     * @author lxc
     * @date 2024-03-04 11:34:58
     */
    @Permission
    @ResponseBody
    @PostMapping("/testpaper/delete")
    @BusinessLog(title = "问卷列表_删除", opType = LogAnnotionOpTypeEnum.DELETE)
    public ResponseData delete(@RequestBody @Validated(TestpaperParam.delete.class) List<TestpaperParam> testpaperParamList) {
        testpaperService.delete(testpaperParamList);
        return new SuccessResponseData();
    }

    /**
     * 修改问卷状态
     *
     * @author lxc
     * @date 2024-03-04 11:34:58
     */
    @Permission
    @ResponseBody
    @PostMapping("/testpaper/editState")
    @BusinessLog(title = "问卷列表_删除", opType = LogAnnotionOpTypeEnum.DELETE)
    public ResponseData editState(@RequestBody Testpaper testpaper) {
        testpaperService.editState(testpaper);
        return new SuccessResponseData();
    }

    /**
     * 编辑问卷列表
     *
     * @author lxc
     * @date 2024-03-04 11:34:58
     */
    @Permission
    @ResponseBody
    @PostMapping("/testpaper/edit")
    @BusinessLog(title = "问卷列表_编辑", opType = LogAnnotionOpTypeEnum.EDIT)
    public ResponseData edit(@RequestBody @Validated(TestpaperParam.edit.class) TestpaperParam testpaperParam) {
        testpaperService.edit(testpaperParam);
        return new SuccessResponseData();
    }

    /**
     * 查看问卷列表
     *
     * @author lxc
     * @date 2024-03-04 11:34:58
     */
    @Permission
    @ResponseBody
    @GetMapping("/testpaper/detail")
    @BusinessLog(title = "问卷列表_查看", opType = LogAnnotionOpTypeEnum.DETAIL)
    public ResponseData detail(TestpaperParam testpaperParam) {
        return new SuccessResponseData(testpaperService.detail(testpaperParam));
    }

    /**
     * 查看每套试卷的详情
     *
     * @author lxc
     * @date 2024-03-04 11:50:58
     */
    @Permission
    @ResponseBody
    @GetMapping("/testpaper/detailList")
    @BusinessLog(title = "问卷列表_查看", opType = LogAnnotionOpTypeEnum.DETAIL)
    public ResponseData detailList(TestpaperParam testpaperParam) {
        JSONObject jsonObject = new JSONObject();
        List<Testpapermx> testpapermxList = testpaperService.detail(testpaperParam);
        Testpaper testpaper = testpaperService.getById(testpaperParam.getTestpaperId());
        jsonObject.put("pd", testpaper);
        List<Testpapermx> radios = null;//单选存放集合
        List<Testpapermx> mul = null;//多选存放集合
        List<Testpapermx> jud = null;//判断存放集合
        List<Testpapermx> comple = null;//填空存放集合
        List<Testpapermx> larg = null;//问答存放集合
        for (Testpapermx testpapermx : testpapermxList) {
            String ArrayDATA_IDS[] = testpapermx.getSelectedtopics().split(",");
            String type = testpapermx.getType();
            switch (type) {
                case "0":
                    List<Map<String, Object>> singleelectionList = singleelectionService.getListByIds(ArrayDATA_IDS);
                    //根据用户id,查询是否已经填写调查问卷，填写了查询出对应结果
                    for (Map map : singleelectionList) {
                        List<Map<String, Object>> list = singleelectionService.queryAnswerByIds(testpaperParam.getId(), testpaperParam.getUserId(), map.get("id").toString());
                        if (list.size() > 0) {
                            map.put("answer", list.get(0).get("USERANSWER"));
                        } else {
                            break;
                        }
                    }
                    //处理添加多条数据合并成一条数据
                    if (radios == null) {
                        radios = new ArrayList<>();
                        radios.add(testpapermx);
                        radios.get(0).setMapList(singleelectionList);
                    } else {
                        radios.get(0).getMapList().addAll(singleelectionList);
                    }
                    break;
                case "1":
                    List<Map<String, Object>> multipleselectionList = multipleselectionService.getListByIds(ArrayDATA_IDS);
                    if (mul == null) {
                        mul = new ArrayList<>();
                        mul.add(testpapermx);
                        mul.get(0).setMapList(multipleselectionList);
                    } else {
                        radios.get(0).getMapList().addAll(multipleselectionList);
                    }
                    break;
                case "2":
                    List<Map<String, Object>> judgementquestionList = judgementquestionService.getListByIds(ArrayDATA_IDS);
                    if (jud == null) {
                        jud = new ArrayList<>();
                        jud.add(testpapermx);
                        jud.get(0).setMapList(judgementquestionList);
                    } else {
                        jud.get(0).getMapList().addAll(judgementquestionList);
                    }
                    break;
                case "3":
                    List<Map<String, Object>> completionList = completionService.getListByIds(ArrayDATA_IDS);
                    if (comple == null) {
                        comple = new ArrayList<>();
                        comple.add(testpapermx);
                        comple.get(0).setMapList(completionList);
                    } else {
                        comple.get(0).getMapList().addAll(completionList);
                    }
                    break;
                case "4":
                    List<Map<String, Object>> largequestionList = largequestionService.getListByIds(ArrayDATA_IDS);
                    for (Map map : largequestionList) {
                        List<Map<String, Object>> list = singleelectionService.queryLargeAnswerByIds(testpaperParam.getId(), testpaperParam.getUserId(), map.get("id").toString());
                        if (list.size() > 0) {
                            map.put("answer", list.get(0).get("USERANSWER"));
                        } else {
                            break;
                        }
                    }
                    if (larg == null) {
                        larg = new ArrayList<>();
                        larg.add(testpapermx);
                        larg.get(0).setMapList(largequestionList);
                    } else {
                        larg.get(0).getMapList().addAll(largequestionList);
                    }
                    break;
            }
        }
        if (mul != null) {
            radios.addAll(mul);
        }
        if (jud != null) {
            radios.addAll(jud);
        }
        if (comple != null) {
            radios.addAll(comple);
        }
        if (larg != null) {
            radios.addAll(larg);
        }
        jsonObject.put("testpapermxList", radios);
        return new SuccessResponseData(jsonObject);
    }

    /**
     * 问卷列表列表
     *
     * @author lxc
     * @date 2024-03-04 11:34:58
     */
    @Permission
    @ResponseBody
    @GetMapping("/testpaper/list")
    @BusinessLog(title = "问卷列表_列表", opType = LogAnnotionOpTypeEnum.QUERY)
    public ResponseData list(TestpaperParam testpaperParam) {
        return new SuccessResponseData(testpaperService.list(testpaperParam));
    }

    /**
     * 获取随机问题
     *
     * @return
     */
    @GetMapping(value = "/testpaper/automatic")
    @ResponseBody
    public ResponseData getRandom(@RequestParam("txxz") String txxz, @RequestParam("tx") String tx) {
        Map<String, Object> map = new HashMap<>();
        map.put("TABN", txxz);
        map.put("QNUMBER", tx);
        List<Map<String, Object>> list = testpaperService.getSjData(map);
        return new SuccessResponseData(list);
    }

    /**
     * 单选选择页面
     *
     * @return
     */
    @GetMapping("/testpaper/dxWindow")
    public String dxWindow() {
        return "system/sysQuestion/radio/index_window.html";
    }

    /**
     * 多选选择页面
     *
     * @return
     */
    @GetMapping("/testpaper/muWindow")
    public String muWindow() {
        return "system/sysQuestion/multiple/index_window.html";
    }

    /**
     * 判断选择页面
     *
     * @return
     */
    @GetMapping("/testpaper/juWindow")
    public String juWindow() {
        return "system/sysQuestion/judgementquestion/index_window.html";
    }

    /**
     * 填空选择页面
     *
     * @return
     */
    @GetMapping("/testpaper/comWindow")
    public String comWindow() {
        return "system/sysQuestion/completion/index_window.html";
    }

    /**
     * 问答选择页面
     *
     * @return
     */
    @GetMapping("/testpaper/larWindow")
    public String larWindow() {
        return "system/sysQuestion/largequestion/index_window.html";
    }

    /**
     * 培训层次
     *
     * @author lxc
     * @date 2024-07-01 11:34:58
     */
    @Permission
    @ResponseBody
    @GetMapping("/testpaper/surveyInfo")
    @BusinessLog(title = "培训层次", opType = LogAnnotionOpTypeEnum.QUERY)
    public ResponseData surveyInfo(Long orgId) {
        //如果未传入所属单位，默认使用当前用户所属单位查询数据
        if (orgId == null) {
            orgId = LoginContextHolder.me().getSysLoginUser().getLoginEmpInfo().getOrgId();
            if (LoginContextHolder.me().isSuperAdmin()) {
                orgId = 0L;
            }
        }
        return new SuccessResponseData(testpaperService.surveyInfo(orgId));
    }

    /**
     * 问卷详细统计
     *
     * @author lxc
     * @date 2024-07-01 11:34:58
     */
    @Permission
    @ResponseBody
    @GetMapping("/testpaper/surveyInfoDetail")
    @BusinessLog(title = "问卷详细统计", opType = LogAnnotionOpTypeEnum.QUERY)
    public ResponseData surveyInfoDetail(TestpaperParam testpaperParam) {
        return new SuccessResponseData(testpaperService.surveyInfoDetail());
    }

    /**
     * 问卷详细统计
     *
     * @author lxc
     * @date 2024-07-01 11:34:58
     */
    @Permission
    @ResponseBody
    @GetMapping("/testpaper/progressDetail")
    @BusinessLog(title = "问卷详细统计", opType = LogAnnotionOpTypeEnum.QUERY)
    public ResponseData progressDetail(TestpaperParam testpaperParam) {
        return new SuccessResponseData(testpaperService.progressDetail());
    }

    /**
     * 获取所有调查问卷
     *
     * @author 李兴超
     * @date 2024-07-01 10:31:03
     */
    @Permission
    @ResponseBody
    @PostMapping("/testpaper/getSurver")
    @BusinessLog(title = "课程管理表_查询", opType = LogAnnotionOpTypeEnum.QUERY)
    public ResponseData getSurver(Testpaper testpaper) {
        return new SuccessResponseData(testpaperService.getSurver(testpaper));
    }

    /**
     * 问卷分析
     *
     * @author lxc
     * @date 2024-08-23 11:34:58
     */
    @GetMapping("/testpaper/dataAnaly")
    public String dataAnaly() {
        return PATH_PREFIX + "dataAnaly.html";
    }

    /**
     * 问卷参加单位统计
     *
     * @param testpaperId 问卷id
     * @author ssh
     * @date 2024-08-27 19:34:58
     */
    @Permission
    @GetMapping("/testpaper/queryOrgNames")
    @ResponseBody
    @BusinessLog(title = "问卷参加单位统计", opType = LogAnnotionOpTypeEnum.QUERY)
    public List<String> queryOrgNames(String testpaperId) {
        return testpaperService.queryOrgNames(testpaperId);
    }

    /**
     * 问卷统计
     *
     * @param testpaperId 问卷id
     * @author ssh
     * @date 2024-08-27 19:34:58
     */
    @Permission
    @GetMapping("/testpaper/statisticsInfo")
    @ResponseBody
    @BusinessLog(title = "问卷统计", opType = LogAnnotionOpTypeEnum.QUERY)
    public List<Map<String, Object>> statisticsInfo(String testpaperId, Long orgId) {
        //如果未传入所属单位，默认使用当前用户所属单位查询数据
        if (orgId == null) {
            orgId = LoginContextHolder.me().getSysLoginUser().getLoginEmpInfo().getOrgId();
            if (LoginContextHolder.me().isSuperAdmin()) {
                orgId = 0L;
            }
        }
        return testpaperService.statisticsInfo(testpaperId, orgId);
    }

    /**
     * 问答题展现
     *
     * @param testpaperId 问卷id
     * @author ssh
     * @date 2024-08-27 19:34:58
     */
    @Permission
    @GetMapping("/testpaper/interlocution")
    @ResponseBody
    @BusinessLog(title = "问卷统计展现", opType = LogAnnotionOpTypeEnum.QUERY)
    public PageResult<Map<String, Object>> statisticsInterlocution(String testpaperId, Long orgId) {
        //如果未传入所属单位，默认使用当前用户所属单位查询数据
        if (orgId == null) {
            orgId = LoginContextHolder.me().getSysLoginUser().getLoginEmpInfo().getOrgId();
            if (LoginContextHolder.me().isSuperAdmin()) {
                orgId = 0L;
            }
        }
        PageResult<Map<String, Object>> jsonObjectPageResult = new PageResult<>();
        jsonObjectPageResult.setCode(0);
        jsonObjectPageResult.setMsg("请求成功");
        jsonObjectPageResult.setPage(1);
        jsonObjectPageResult.setLimit(100);
        jsonObjectPageResult.setCount(100);
        jsonObjectPageResult.setData(testpaperService.statisticsInterlocution(testpaperId, orgId));
        return jsonObjectPageResult;
    }

    /**
     * 问卷统计导出
     *
     * @param testpaperId 问卷id
     * @author ssh
     * @date 2024-08-27 19:34:58
     */
    @Permission
    @GetMapping("/testpaper/statisticsInfoExp")
    @BusinessLog(title = "问卷统计导出", opType = LogAnnotionOpTypeEnum.EXPORT)
    public void statisticsInfoExp(HttpServletResponse response, String testpaperId, Long orgId) {
        //如果未传入所属单位，默认使用当前用户所属单位查询数据
        if (orgId == null) {
            orgId = LoginContextHolder.me().getSysLoginUser().getLoginEmpInfo().getOrgId();
            if (LoginContextHolder.me().isSuperAdmin()) {
                orgId = 0L;
            }
        }
        try {
            List<Map<String, Object>> maps = testpaperService.statisticsInfo(testpaperId, orgId);
            String templateFileName = this.getClass().getResource("/").getPath() + "template" + File.separator + "问卷统计模板.xlsx";
            templateFileName = URLDecoder.decode(templateFileName, "utf-8"); //解决路径包含中文的情况

            File file = new File(templateFileName);

            // 获取模板数据
            TemplateExportParams params = new TemplateExportParams(file.getAbsolutePath(), 0);

            HashMap<String, Object> workbookNeedMap = new HashMap<>();
            workbookNeedMap.put("maps", maps);

            // 导出，并获取工作簿
            Workbook workbook = ExcelExportUtil.exportExcel(params, workbookNeedMap);

            // ================= 结束输出 ==================
            // 输出
            responseWorkbook(response, workbook, "问卷统计导出.xlsx");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    /**
     * 导出 Excel
     *
     * @param response
     * @param workbook
     * @param fileName
     */
    private static void responseWorkbook(HttpServletResponse response, Workbook workbook, String fileName) {
        try {
            response.setHeader("Content-disposition", "attachment;" + "filename*=utf-8''" + URLEncoder.encode(fileName, "UTF-8"));
            response.setContentType("application/octet-stream; charset=UTF-8");
            workbook.write(response.getOutputStream());

            workbook.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


}
